package com.zf.yichat.service.impl;

import com.zf.yichat.mapper.StMallOrderMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.StMallOrder;
import com.zf.yichat.model.User;
import com.zf.yichat.model.UserBalance;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.StMallOrderService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.BalanceType;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class StMallOrderServiceImpl implements StMallOrderService {

    @Autowired
    private StMallOrderMapper mallOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BalanceService balanceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FsResponse payment(Long userId, String orderNo, BigDecimal orderAmount, BigDecimal payAmount, BigDecimal discountsAmount, Integer goodsId, Integer goodsCount, String emsType) {


        User user = userMapper.queryUserByParam("", userId);
        if (null == user) {
            return FsResponseGen.failMsg("用户不存在，userId: " + userId);
        }

        UserBalance balance = balanceService.selectByUserId(userId);
        Contracts.assertTrue(balance.getIncomeBalance().compareTo(payAmount) >= 0, YiChatMsgCode.PACKET_CREATE_NO_ENOUGH_BALANCE.msg());

        // 更新用户余额
        balanceService.update(userId, BalanceType.USER_PAYMENT_MALL_ORDER, payAmount, userId, BalanceType.USER_PAYMENT_MALL_ORDER.getDesc());

        StMallOrder mallOrder = new StMallOrder();
        mallOrder.setUserId(userId);
        mallOrder.setOrderNo(orderNo);
        mallOrder.setDiscountsAmount(discountsAmount);
        mallOrder.setEmsType(emsType);
        mallOrder.setGoodsCount(goodsCount);
        mallOrder.setGoodsId(goodsId);
        mallOrder.setOrderAmount(orderAmount);
        mallOrder.setPayAmount(payAmount);
        mallOrder.setPayTime(new Date());
        mallOrderMapper.insertSelective(mallOrder);

        return FsResponseGen.successData(mallOrder);
    }
}
